// 数据操作文件模块
// 只处理数据，不关心业务

const fs = require('fs');
const dbPath = './db.json';

// 获取所有学生列表
// callback 上层定义，下层调用
exports.findAll = function (callback) {
	fs.readFile(dbPath, 'utf8', function (err, data) {
		if (err) {
			return callback(err);
		}
		callback(null, JSON.parse(data).students);
	})
}

// 根据ID查询学生
exports.findById = function (id, callback) {
	fs.readFile(dbPath, 'utf8', function (err, data) {
		if (err) {
			return callback(err);
		}
		const students = JSON.parse(data).students;
		const student = students.find(item => {
			return item.id == id;
		})
		callback(null, student);
	})
}

// 添加保存学生
exports.save = function (student, callback) {
	fs.readFile(dbPath, 'utf8', function (err, data) {
		if (err) {
			return callback(err);
		}
		const students = JSON.parse(data).students;
		student.id = students[students.length - 1].id + 1;
		students.push(student);
		const fileData = JSON.stringify({
			students: students
		});
		fs.writeFile(dbPath, fileData, function (err) {
			if (err) {
				return callback(err);
			}
			callback(null);
		});
	})
}

// 更新学生
exports.updateById = function (student, callback) {
	fs.readFile(dbPath, 'utf8', function (err, data) {
		if (err) {
			return callback(err);
		}
		const students = JSON.parse(data).students;
		const curStudent = students.find(item => {
			return item.id == student.id;
		});
		for (let key in student) {
			curStudent[key] = student[key];
		}
		const fileData = JSON.stringify({
			students: students
		})
		fs.writeFile(dbPath, fileData, function (err) {
			if (err) {
				return callback(err);
			}
			callback(null);
		});
	})
}

// 删除学生
exports.delete = function (id, callback) {
	fs.readFile(dbPath, 'utf8', function (err, data) {
		if (err) {
			return callback(err);
		}
		const students = JSON.parse(data).students;
		const studentIndex = students.findIndex(item => {
			return item.id == id;
		})
		if (studentIndex !== -1) { students.splice(studentIndex, 1) }
		const fileData = JSON.stringify({
			students: students
		})
		fs.writeFile(dbPath, fileData, function (err) {
			if (err) {
				return callback(err);
			}
			callback(null);
		});
	})
}